home *** CD-ROM | disk | FTP | other *** search
/ MacFormat 1995 March / macformat-022.iso / Shareware City / Developers / GNU Diff Sources / GNU DIFF 1.15b Sources / analyze.c < prev    next >
Encoding:
C/C++ Source or Header  |  1994-08-26  |  28.5 KB  |  1,054 lines  |  [TEXT/ALFA]

  1. /* Analyze file differences for GNU DIFF.
  2.    Copyright (C) 1988, 1989 Free Software Foundation, Inc.
  3.  
  4. This file is part of GNU DIFF.
  5.  
  6. GNU DIFF is free software; you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation; either version 1, or (at your option)
  9. any later version.
  10.  
  11. GNU DIFF is distributed in the hope that it will be useful,
  12. but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14. GNU General Public License for more details.
  15.  
  16. You should have received a copy of the GNU General Public License
  17. along with GNU DIFF; see the file COPYING.  If not, write to
  18. the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
  19.  
  20. /* The basic algorithm is described in: 
  21.    "An O(ND) Difference Algorithm and its Variations", Eugene Myers,
  22.    Algorithmica Vol. 1 No. 2, 1986, p 251.  */
  23.  
  24. #include "diff.h"
  25.  
  26. struct change *find_change ();
  27. void finish_output ();
  28. void print_context_header ();
  29. void print_context_script ();
  30. void print_ed_script ();
  31. void print_ifdef_script ();
  32. void print_normal_script ();
  33. void print_rcs_script ();
  34. void pr_forward_ed_script ();
  35. void setup_output ();
  36.  
  37. extern int no_discards;
  38.  
  39. static LONG *xvec, *yvec;    /* Vectors being compared. */
  40. static LONG *fdiag;        /* Vector, indexed by diagonal, containing
  41.                    the X coordinate of the point furthest
  42.                    along the given diagonal in the forward
  43.                    search of the edit matrix. */
  44. static LONG *bdiag;        /* Vector, indexed by diagonal, containing
  45.                    the X coordinate of the point furthest
  46.                    along the given diagonal in the backward
  47.                    search of the edit matrix. */
  48.  
  49. /* Find the midpoint of the shortest edit script for a specified
  50.    portion of the two files.
  51.  
  52.    We scan from the beginnings of the files, and simultaneously from the ends,
  53.    doing a breadth-first search through the space of edit-sequence.
  54.    When the two searches meet, we have found the midpoint of the shortest
  55.    edit sequence.
  56.  
  57.    The value returned is the number of the diagonal on which the midpoint lies.
  58.    The diagonal number equals the number of inserted lines minus the number
  59.    of deleted lines (counting only lines before the midpoint).
  60.    The edit cost is stored into *COST; this is the total number of
  61.    lines inserted or deleted (counting only lines before the midpoint).
  62.  
  63.    This function assumes that the first lines of the specified portions
  64.    of the two files do not match, and likewise that the last lines do not
  65.    match.  The caller must trim matching lines from the beginning and end
  66.    of the portions it is going to specify.
  67.  
  68.    Note that if we return the "wrong" diagonal value, or if
  69.    the value of bdiag at that diagonal is "wrong",
  70.    the worst this can do is cause suboptimal diff output.
  71.    It cannot cause incorrect diff output.  */
  72.  
  73. static LONG
  74. diag (xoff, xlim, yoff, ylim, cost)
  75.     LONG xoff, xlim, yoff, ylim;
  76.      int *cost;
  77. {
  78.     LONG *const fd = fdiag;    /* Give the compiler a chance. */
  79.     LONG *const bd = bdiag;    /* Additional help for the compiler. */
  80.     LONG *const xv = xvec;        /* Still more help for the compiler. */
  81.     LONG *const yv = yvec;        /* And more and more . . . */
  82.     const LONG dmin = xoff - ylim;    /* Minimum valid diagonal. */
  83.     const LONG dmax = xlim - yoff;    /* Maximum valid diagonal. */
  84.     const LONG fmid = xoff - yoff;    /* Center diagonal of top-down search. */
  85.     const LONG bmid = xlim - ylim;    /* Center diagonal of bottom-up search. */
  86.     LONG fmin = fmid, fmax = fmid;    /* Limits of top-down search. */
  87.     LONG bmin = bmid, bmax = bmid;    /* Limits of bottom-up search. */
  88.   int c;            /* Cost. */
  89.   int odd = fmid - bmid & 1;    /* True if southeast corner is on an odd
  90.                    diagonal with respect to the northwest. */
  91.  
  92.   fd[fmid] = xoff;
  93.   bd[bmid] = xlim;
  94.  
  95.   for (c = 1;; ++c)
  96.     {
  97.         LONG d;            /* Active diagonal. */
  98.       int big_snake = 0;
  99.  
  100.       /* Extend the top-down search by an edit step in each diagonal. */
  101.       fmin > dmin ? fd[--fmin - 1] = -1 : ++fmin;
  102.       fmax < dmax ? fd[++fmax + 1] = -1 : --fmax;
  103.       for (d = fmax; d >= fmin; d -= 2)
  104.     {
  105.             LONG x, y, oldx, tlo = fd[d - 1], thi = fd[d + 1];
  106.  
  107.       if (tlo >= thi)
  108.         x = tlo + 1;
  109.       else
  110.         x = thi;
  111.       oldx = x;
  112.       y = x - d;
  113.       while (x < xlim && y < ylim && xv[x] == yv[y])
  114.         ++x, ++y;
  115.       if (x - oldx > 20)
  116.         big_snake = 1;
  117.       fd[d] = x;
  118.       if (odd && bmin <= d && d <= bmax && bd[d] <= fd[d])
  119.         {
  120.           *cost = 2 * c - 1;
  121.           return d;
  122.         }
  123.     }
  124.  
  125.       /* Similar extend the bottom-up search. */
  126.         bmin > dmin ? bd[--bmin - 1] = SIZET_MAX : ++bmin;
  127.         bmax < dmax ? bd[++bmax + 1] = SIZET_MAX : --bmax;
  128.  
  129.       for (d = bmax; d >= bmin; d -= 2)
  130.     {
  131.             LONG x, y, oldx, tlo = bd[d - 1], thi = bd[d + 1];
  132.  
  133.       if (tlo < thi)
  134.         x = tlo;
  135.       else
  136.         x = thi - 1;
  137.       oldx = x;
  138.       y = x - d;
  139.       while (x > xoff && y > yoff && xv[x - 1] == yv[y - 1])
  140.         --x, --y;
  141.       if (oldx - x > 20)
  142.         big_snake = 1;
  143.       bd[d] = x;
  144.       if (!odd && fmin <= d && d <= fmax && bd[d] <= fd[d])
  145.         {
  146.           *cost = 2 * c;
  147.           return d;
  148.         }
  149.     }
  150.  
  151.       /* Heuristic: check occasionally for a diagonal that has made
  152.      lots of progress compared with the edit distance.
  153.      If we have any such, find the one that has made the most
  154.      progress and return it as if it had succeeded.
  155.  
  156.      With this heuristic, for files with a constant small density
  157.      of changes, the algorithm is linear in the file size.  */
  158.  
  159.       if (c > 200 && big_snake && heuristic)
  160.     {
  161.             LONG best;
  162.             LONG bestpos;
  163.  
  164.       best = 0;
  165.       for (d = fmax; d >= fmin; d -= 2)
  166.         {
  167.                 LONG dd = d - fmid;
  168.           if ((fd[d] - xoff)*2 - dd > 12 * (c + (dd > 0 ? dd : -dd)))
  169.         {
  170.           if (fd[d] * 2 - dd > best
  171.               && fd[d] - xoff > 20
  172.               && fd[d] - d - yoff > 20)
  173.             {
  174.               int k;
  175.                         LONG x = fd[d];
  176.  
  177.               /* We have a good enough best diagonal;
  178.              now insist that it end with a significant snake.  */
  179.               for (k = 1; k <= 20; k++)
  180.             if (xvec[x - k] != yvec[x - d - k])
  181.               break;
  182.  
  183.               if (k == 21)
  184.             {
  185.               best = fd[d] * 2 - dd;
  186.               bestpos = d;
  187.             }
  188.             }
  189.         }
  190.         }
  191.       if (best > 0)
  192.         {
  193.           *cost = 2 * c - 1;
  194.           return bestpos;
  195.         }
  196.  
  197.       best = 0;
  198.       for (d = bmax; d >= bmin; d -= 2)
  199.         {
  200.                 LONG dd = d - bmid;
  201.           if ((xlim - bd[d])*2 + dd > 12 * (c + (dd > 0 ? dd : -dd)))
  202.         {
  203.           if ((xlim - bd[d]) * 2 + dd > best
  204.               && xlim - bd[d] > 20
  205.               && ylim - (bd[d] - d) > 20)
  206.             {
  207.               /* We have a good enough best diagonal;
  208.              now insist that it end with a significant snake.  */
  209.               int k;
  210.                         LONG x = bd[d];
  211.  
  212.               for (k = 0; k < 20; k++)
  213.             if (xvec[x + k] != yvec[x - d + k])
  214.               break;
  215.               if (k == 20)
  216.             {
  217.               best = (xlim - bd[d]) * 2 + dd;
  218.               bestpos = d;
  219.             }
  220.             }
  221.         }
  222.         }
  223.       if (best > 0)
  224.         {
  225.           *cost = 2 * c - 1;
  226.           return bestpos;
  227.         }
  228.     }
  229.     }
  230. }
  231.  
  232. /* Compare in detail contiguous subsequences of the two files
  233.    which are known, as a whole, to match each other.
  234.  
  235.    The results are recorded in the vectors files[N].changed_flag, by
  236.    storing a 1 in the element for each line that is an insertion or deletion.
  237.  
  238.    The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
  239.  
  240.    Note that XLIM, YLIM are exclusive bounds.
  241.    All line numbers are origin-0 and discarded lines are not counted.  */
  242.  
  243. static diff_err
  244. compareseq (xoff, xlim, yoff, ylim)
  245.     LONG xoff, xlim, yoff, ylim;
  246. {
  247.   /* Slide down the bottom initial diagonal. */
  248.   while (xoff < xlim && yoff < ylim && xvec[xoff] == yvec[yoff])
  249.     ++xoff, ++yoff;
  250.   /* Slide up the top initial diagonal. */
  251.   while (xlim > xoff && ylim > yoff && xvec[xlim - 1] == yvec[ylim - 1])
  252.     --xlim, --ylim;
  253.   
  254.   /* Handle simple cases. */
  255.   if (xoff == xlim)
  256.     while (yoff < ylim)
  257.       files[1].changed_flag[files[1].realindexes[yoff++]] = 1;
  258.   else if (yoff == ylim)
  259.     while (xoff < xlim)
  260.       files[0].changed_flag[files[0].realindexes[xoff++]] = 1;
  261.   else
  262.     {
  263.         int c;
  264.         LONG    d, f, b;
  265.         int    ret_err;
  266.  
  267.       /* Find a point of correspondence in the middle of the files.  */
  268.  
  269.       d = diag (xoff, xlim, yoff, ylim, &c);
  270.       f = fdiag[d];
  271.       b = bdiag[d];
  272.  
  273.       if (c == 1)
  274.     {
  275.       /* This should be impossible, because it implies that
  276.          one of the two subsequences is empty,
  277.          and that case was handled above without calling `diag'.
  278.          Let's verify that this is true.  */
  279.             errno = internal_err;
  280.             fatal ("Internal error: compareseq: c != 1");
  281.             return (errno);
  282. #if 0
  283.       /* The two subsequences differ by a single insert or delete;
  284.          record it and we are done.  */
  285.       if (d < xoff - yoff)
  286.         files[1].changed_flag[files[1].realindexes[b - d - 1]] = 1;
  287.       else
  288.         files[0].changed_flag[files[0].realindexes[b]] = 1;
  289. #endif
  290.     }
  291.       else
  292.     {
  293.       /* Use that point to split this problem into two subproblems.  */
  294.             if ( ret_err = compareseq (xoff, b, yoff, b - d) )
  295.                   return (ret_err);
  296.       /* This used to use f instead of b,
  297.          but that is incorrect!
  298.          It is not necessarily the case that diagonal d
  299.          has a snake from b to f.  */
  300.             if ( ret_err = compareseq (b, xlim, b - d, ylim) )
  301.                   return (ret_err);
  302.     }
  303.     }
  304.     return (0);
  305. }
  306.  
  307. /* Discard lines from one file that have no matches in the other file.
  308.  
  309.    A line which is discarded will not be considered by the actual
  310.    comparison algorithm; it will be as if that line were not in the file.
  311.    The file's `realindexes' table maps virtual line numbers
  312.    (which don't count the discarded lines) into real line numbers;
  313.    this is how the actual comparison algorithm produces results
  314.    that are comprehensible when the discarded lines are counted.
  315.  
  316.    When we discard a line, we also mark it as a deletion or insertion
  317.    so that it will be printed in the output.
  318.  
  319.    This routine returns an error code if there were any problems allocating
  320.    memory.  */
  321.  
  322. diff_err
  323. discard_confusing_lines (filevec)
  324.      struct file_data filevec[];
  325. {
  326.     unsigned int f;
  327.     unsigned LONG    i;
  328.   char *discarded[2];
  329.     LONG *equiv_count[2];
  330.     diff_err    error = 0;
  331.  
  332.   /* Allocate our results.  */
  333.   for (f = 0; f < 2; f++)
  334.     {
  335.       filevec[f].undiscarded
  336.             = (LONG *) xmalloc (filevec[f].buffered_lines * sizeof (*filevec[f].undiscarded));
  337.       filevec[f].realindexes
  338.             = (LONG *) xmalloc (filevec[f].buffered_lines * sizeof (*filevec[f].realindexes));
  339.     }
  340.  
  341.   /* Set up equiv_count[F][I] as the number of lines in file F
  342.      that fall in equivalence class I.  */
  343.  
  344.     equiv_count[0] = (LONG *) xmalloc (filevec[0].equiv_max * sizeof (equiv_count[0][0]));
  345.     bzero (equiv_count[0], filevec[0].equiv_max * sizeof (equiv_count[0][0]));
  346.     equiv_count[1] = (LONG *) xmalloc (filevec[1].equiv_max * sizeof (equiv_count[1][0]));
  347.     bzero (equiv_count[1], filevec[1].equiv_max * sizeof (equiv_count[1][0]));
  348.  
  349.     /* Abort this routine if there were memory errors. */
  350.     if ( ! filevec[0].undiscarded || ! filevec[1].undiscarded
  351.         || ! equiv_count[0] || ! equiv_count[1] )
  352.     {
  353.         error = memory_err;
  354.         goto    done;
  355.     }
  356.  
  357.     for (i = 0; i < filevec[0].buffered_lines; ++i)
  358.     ++equiv_count[0][filevec[0].equivs[i]];
  359.     for (i = 0; i < filevec[1].buffered_lines; ++i)
  360.     ++equiv_count[1][filevec[1].equivs[i]];
  361.  
  362.   /* Set up tables of which lines are going to be discarded.  */
  363.  
  364.     discarded[0] = (char *) xmalloc (filevec[0].buffered_lines);
  365.     discarded[1] = (char *) xmalloc (filevec[1].buffered_lines);
  366.     bzero (discarded[0], filevec[0].buffered_lines);
  367.     bzero (discarded[1], filevec[1].buffered_lines);
  368.  
  369.     /* Abort this routine if there were memory errors. */
  370.     if ( ! discarded[0] || ! discarded[1] )
  371.     {
  372.         error = memory_err;
  373.         goto    done;
  374.     }
  375.     
  376.   /* Mark to be discarded each line that matches no line of the other file.
  377.      If a line matches many lines, mark it as provisionally discardable.  */
  378.  
  379.   for (f = 0; f < 2; f++)
  380.     {
  381.         unsigned LONG end = filevec[f].buffered_lines;
  382.       char *discards = discarded[f];
  383.         LONG *counts = equiv_count[1 - f];
  384.         LONG *equivs = filevec[f].equivs;
  385.       unsigned LONG many = 5;
  386.       unsigned LONG tem = end / 64;
  387.  
  388.       /* Multiply MANY by approximate square root of number of lines.
  389.      That is the threshold for provisionally discardable lines.  */
  390.       while ((tem = tem >> 2) > 0)
  391.     many *= 2;
  392.  
  393.       for (i = 0; i < end; i++)
  394.     {
  395.             LONG nmatch;
  396.       if (equivs[i] == 0)
  397.         continue;
  398.       nmatch = counts[equivs[i]];
  399.       if (nmatch == 0)
  400.         discards[i] = 1;
  401.       else if (nmatch > many)
  402.         discards[i] = 2;
  403.     }
  404.     }
  405.  
  406.   /* Don't really discard the provisional lines except when they occur
  407.      in a run of discardables, with nonprovisionals at the beginning
  408.      and end.  */
  409.  
  410.   for (f = 0; f < 2; f++)
  411.     {
  412.         unsigned LONG end = filevec[f].buffered_lines;
  413.         register char *discards = discarded[f];
  414.  
  415.       for (i = 0; i < end; i++)
  416.       {
  417.       /* Cancel provisional discards not in middle of run of discards.  */
  418.       if (discards[i] == 2)
  419.           discards[i] = 0;
  420.       else if (discards[i] != 0)
  421.         {
  422.           /* We have found a nonprovisional discard.  */
  423.           register LONG j;
  424.           unsigned LONG length;
  425.           unsigned LONG provisional = 0;
  426.  
  427.         /* Find end of this run of discardable lines.
  428.            Count how many are provisionally discardable.  */
  429.         for (j = i; j < end; j++)
  430.           {
  431.         if (discards[j] == 0)
  432.           break;
  433.         if (discards[j] == 2)
  434.           ++provisional;
  435.           }
  436.  
  437.           /* Cancel provisional discards at end, and shrink the run.  */
  438.         while (j > i && discards[j - 1] == 2)
  439.         discards[--j] = 0, --provisional;
  440.  
  441.         /* Now we have the length of a run of discardable lines
  442.            whose first and last are not provisional.  */
  443.         length = j - i;
  444.  
  445.           /* If 1/4 of the lines in the run are provisional,
  446.            cancel discarding of all provisional lines in the run.  */
  447.           if (provisional * 4 > length)
  448.           {
  449.         while (j > i)
  450.           if (discards[--j] == 2)
  451.             discards[j] = 0;
  452.           }
  453.         else
  454.           {
  455.           register unsigned LONG consec;
  456.           unsigned LONG minimum = 1;
  457.           unsigned LONG tem = length / 4;
  458.  
  459.           /* MINIMUM is approximate square root of LENGTH/4.
  460.              A subrun of two or more provisionals can stand
  461.              when LENGTH is at least 16.
  462.              A subrun of 4 or more can stand when LENGTH >= 64.  */
  463.           while ((tem = tem >> 2) > 0)
  464.             minimum *= 2;
  465.           minimum++;
  466.  
  467.           /* Cancel any subrun of MINIMUM or more provisionals
  468.              within the larger run.  */
  469.           for (j = 0, consec = 0; j < length; j++)
  470.             if (discards[i + j] != 2)
  471.               consec = 0;
  472.             else if (minimum == ++consec)
  473.               /* Back up to start of subrun, to cancel it all.  */
  474.               j -= consec;
  475.             else if (minimum < consec)
  476.             discards[i + j] = 0;
  477.  
  478.           /* Scan from beginning of run
  479.              until we find 3 or more nonprovisionals in a row
  480.              or until the first nonprovisional at least 8 lines in.
  481.              Until that point, cancel any provisionals.  */
  482.           for (j = 0, consec = 0; j < length; j++)
  483.             {
  484.               if (j >= 8 && discards[i + j] == 1)
  485.             break;
  486.               if (discards[i + j] == 2)
  487.             consec = 0, discards[i + j] = 0;
  488.               else if (discards[i + j] == 0)
  489.             consec = 0;
  490.               else
  491.             consec++;
  492.               if (consec == 3)
  493.             break;
  494.             }
  495.  
  496.           /* I advances to the last line of the run.  */
  497.         i += length - 1;
  498.  
  499.           /* Same thing, from end.  */
  500.           for (j = 0, consec = 0; j < length; j++)
  501.             {
  502.               if (j >= 8 && discards[i - j] == 1)
  503.             break;
  504.           if (discards[i - j] == 2)
  505.             consec = 0, discards[i - j] = 0;
  506.               else if (discards[i - j] == 0)
  507.             consec = 0;
  508.               else
  509.             consec++;
  510.               if (consec == 3)
  511.             break;
  512.             }
  513.           }
  514.       }
  515.     }
  516.     }
  517.  
  518.   /* Actually discard the lines. */
  519.   for (f = 0; f < 2; f++)
  520.     {
  521.       char *discards = discarded[f];
  522.         unsigned LONG end = filevec[f].buffered_lines;
  523.         unsigned LONG j = 0;
  524.       for (i = 0; i < end; ++i)
  525.     if (no_discards || discards[i] == 0)
  526.       {
  527.         filevec[f].undiscarded[j] = filevec[f].equivs[i];
  528.         filevec[f].realindexes[j++] = i;
  529.       }
  530.     else
  531.       filevec[f].changed_flag[i] = 1;
  532.       filevec[f].nondiscarded_lines = j;
  533.     }
  534.  
  535. done:
  536.   free (discarded[1]);
  537.   free (discarded[0]);
  538.   free (equiv_count[1]);
  539.   free (equiv_count[0]);
  540.   if ( error )
  541.   {
  542.       /* Also free other data structures if this was unsuccessful. */
  543.       free (filevec[0].undiscarded);
  544.       free (filevec[0].realindexes);
  545.       free (filevec[1].undiscarded);
  546.       free (filevec[1].realindexes);
  547.   }
  548.   return (error);
  549. }
  550.  
  551. /* Adjust inserts/deletes of blank lines to join changes
  552.    as much as possible.
  553.  
  554.    We do something when a run of changed lines include a blank
  555.    line at one end and have an excluded blank line at the other.
  556.    We are free to choose which blank line is included.
  557.    `compareseq' always chooses the one at the beginning,
  558.    but usually it is cleaner to consider the following blank line
  559.    to be the "change".  The only exception is if the preceding blank line
  560.    would join this change to other changes.  */
  561.  
  562. int inhibit;
  563.  
  564. static void
  565. shift_boundaries (filevec)
  566.      struct file_data filevec[];
  567. {
  568.   int f;
  569.  
  570.   if (inhibit)
  571.     return;
  572.  
  573.   for (f = 0; f < 2; f++)
  574.     {
  575.       char *changed = filevec[f].changed_flag;
  576.       char *other_changed = filevec[1-f].changed_flag;
  577.         LONG i = 0;
  578.         LONG j = 0;
  579.         LONG i_end = filevec[f].buffered_lines;
  580.         LONG preceding = -1;
  581.         LONG other_preceding = -1;
  582.  
  583.       while (1)
  584.     {
  585.             LONG start, end, other_start;
  586.  
  587.       /* Scan forwards to find beginning of another run of changes.
  588.          Also keep track of the corresponding point in the other file.  */
  589.  
  590.       while (i < i_end && changed[i] == 0)
  591.         {
  592.           while (other_changed[j++])
  593.         /* Non-corresponding lines in the other file
  594.            will count as the preceding batch of changes.  */
  595.         other_preceding = j;
  596.           i++;
  597.         }
  598.  
  599.       if (i == i_end)
  600.         break;
  601.  
  602.       start = i;
  603.       other_start = j;
  604.  
  605.       while (1)
  606.         {
  607.           /* Now find the end of this run of changes.  */
  608.  
  609.           while (i < i_end && changed[i] != 0) i++;
  610.           end = i;
  611.  
  612.           /* If the first changed line matches the following unchanged one,
  613.          and this run does not follow right after a previous run,
  614.          and there are no lines deleted from the other file here,
  615.          then classify the first changed line as unchanged
  616.          and the following line as changed in its place.  */
  617.  
  618.           /* You might ask, how could this run follow right after another?
  619.          Only because the previous run was shifted here.  */
  620.  
  621.           if (end != i_end
  622.           && files[f].equivs[start] == files[f].equivs[end]
  623.           && !other_changed[j]
  624.           && end != i_end
  625.           && !((preceding >= 0 && start == preceding)
  626.                || (other_preceding >= 0
  627.                && other_start == other_preceding)))
  628.         {
  629.           changed[end++] = 1;
  630.           changed[start++] = 0;
  631.           ++i;
  632.           /* Since one line-that-matches is now before this run
  633.              instead of after, we must advance in the other file
  634.              to keep in synch.  */
  635.           ++j;
  636.         }
  637.           else
  638.         break;
  639.         }
  640.  
  641.       preceding = i;
  642.       other_preceding = j;
  643.     }
  644.     }
  645. }
  646.  
  647. /* Cons an additional entry onto the front of an edit script OLD.
  648.    LINE0 and LINE1 are the first affected lines in the two files (origin 0).
  649.    DELETED is the number of lines deleted here from file 0.
  650.    INSERTED is the number of lines inserted here in file 1.
  651.  
  652.    If DELETED is 0 then LINE0 is the number of the line before
  653.    which the insertion was done; vice versa for INSERTED and LINE1.  */
  654.  
  655. static struct change *
  656. add_change (xline0, xline1, deleted, inserted, old)
  657.     LONG xline0, xline1, deleted, inserted;
  658.      struct change *old;
  659. {
  660.   struct change *new = (struct change *) xmalloc (sizeof (struct change));
  661.  
  662.     new->line0 = xline0;
  663.     new->line1 = xline1;
  664.     new->line0end = xline0 + deleted - 1;
  665.     new->line1end = xline1 + inserted - 1;
  666.   new->link = old;
  667.   return new;
  668. }
  669.  
  670. /* Scan the tables of which lines are inserted and deleted,
  671.    producing an edit script in reverse order.  */
  672.  
  673. static struct change *
  674. build_reverse_script (filevec)
  675.      struct file_data filevec[];
  676. {
  677.   struct change *script = 0;
  678.   char *changed0 = filevec[0].changed_flag;
  679.   char *changed1 = filevec[1].changed_flag;
  680.     LONG len0 = filevec[0].buffered_lines;
  681.     LONG len1 = filevec[1].buffered_lines;
  682.  
  683.   /* Note that changedN[len0] does exist, and contains 0.  */
  684.  
  685.     LONG i0 = 0, i1 = 0;
  686.  
  687.   while (i0 < len0 || i1 < len1)
  688.     {
  689.       if (changed0[i0] || changed1[i1])
  690.     {
  691.             LONG xline0 = i0, xline1 = i1;
  692.  
  693.       /* Find # lines changed here in each file.  */
  694.       while (changed0[i0]) ++i0;
  695.       while (changed1[i1]) ++i1;
  696.  
  697.       /* Record this change.  */
  698.             script = add_change (xline0, xline1, i0 - xline0, i1 - xline1, script);
  699.     }
  700.  
  701.       /* We have reached lines in the two files that match each other.  */
  702.       i0++, i1++;
  703.     }
  704.  
  705.   return script;
  706. }
  707.  
  708. /* Scan the tables of which lines are inserted and deleted,
  709.    producing an edit script in forward order.  */
  710.  
  711. static struct change *
  712. build_script (filevec)
  713.      struct file_data filevec[];
  714. {
  715.   struct change *script = 0;
  716.   char *changed0 = filevec[0].changed_flag;
  717.   char *changed1 = filevec[1].changed_flag;
  718.     LONG len0 = filevec[0].buffered_lines;
  719.     LONG len1 = filevec[1].buffered_lines;
  720.   LONG i0 = len0, i1 = len1;
  721.  
  722.   /* Note that changedN[-1] does exist, and contains 0.  */
  723.  
  724. #if 0 /* Unnecessary since a line includes its trailing newline.  */
  725.   /* In RCS comparisons, making the existence or nonexistence of trailing
  726.      newlines really matter. */
  727.   if (output_style == OUTPUT_RCS
  728.       && filevec[0].missing_newline != filevec[1].missing_newline)
  729.     changed0[len0 - 1] = changed1[len1 - 1] = 1;
  730. #endif
  731.  
  732.   while (i0 >= 0 || i1 >= 0)
  733.     {
  734.       if (changed0[i0 - 1] || changed1[i1 - 1])
  735.     {
  736.             LONG xline0 = i0, xline1 = i1;
  737.  
  738.       /* Find # lines changed here in each file.  */
  739.       while (changed0[i0 - 1]) --i0;
  740.       while (changed1[i1 - 1]) --i1;
  741.  
  742.       /* Record this change.  */
  743.             script = add_change (i0, i1, xline0 - i0, xline1 - i1, script);
  744.     }
  745.  
  746.       /* We have reached lines in the two files that match each other.  */
  747.       i0--, i1--;
  748.     }
  749.  
  750.   return script;
  751. }
  752.  
  753. #ifndef    EXCLUDE_MAIN
  754.  
  755. /* Report the differences of two files.  DEPTH is the current directory
  756.    depth. */
  757. int
  758. diff_2_files (filevec, depth)
  759.     struct file_data filevec[];
  760.     int depth;
  761.     {
  762.     int    changes;
  763.     int i;
  764.     struct    change *script;
  765.     int    differs;
  766.     
  767.     /* See if the two named files are actually the same physical file.
  768.          If so, we know they are identical without actually reading them.  */
  769.  
  770.     if (output_style != OUTPUT_IFDEF
  771.       && filevec[0].stat.st_ito == filevec[1].stat.st_ito
  772.             && filevec[0].stat.st_dev == filevec[1].stat.st_dev)
  773.         return 0;
  774.  
  775.     script = diff_2_files_no_print (filevec, &differs);
  776.     changes = TRUE;
  777.     if ( ! differs )
  778.         changes = print_results (filevec, script, depth);
  779.     dispose_script (script);
  780.     for (i = 0; i < 2; ++i)
  781.         {
  782.         if (filevec[i].buffer != 0)
  783.             free (filevec[i].buffer);
  784.         free (filevec[i].linbuf);
  785.         }
  786.     return (changes);
  787.     }
  788.  
  789. #endif    EXCLUDE_MAIN
  790.  
  791. /*
  792.  * Report the differences of two files.  DEPTH is the current directory
  793.  * depth.  Before calling this routine, make sure that filevec[0].buffered_chars
  794.  * is the number of characters in the stream to compare, filevec[0].buffer is the
  795.  * pointer to the stream, filevec[0].stat.st_mtime is set to the file time (for
  796.  * output to the user only), and filevec[0].name is the name of the file (for user output).
  797.  * Also, make sure that filevec[1] is set up the same way.  Then, call read_files(filevec).
  798.  * Finally, call this routine.
  799.  *
  800.  * Now, this routine returns a list of "change" records.  It is up to the caller to display
  801.  * this change list in whatever way is appropriate and then to dispose of the list.
  802.  */
  803. struct change *
  804. diff_2_files_no_print (filevec, file_differs)
  805.      struct file_data filevec[];
  806.      int *file_differs;
  807. {
  808.     LONG diags;
  809.     int i;
  810.   struct change *script = NULL;
  811.     int binary;
  812.     int    error = 0;
  813.  
  814.     *file_differs = 0;
  815.  
  816.     binary = read_files (filevec);
  817.     if ( binary < 0 )
  818.     {
  819.         error = binary;
  820.         goto done;
  821.     }
  822.  
  823.     /* If we have detected that file 0 is a binary file,
  824.      compare the two files as binary.  This can happen
  825.      only when the first chunk is read.
  826.      Also, -q means treat all files as binary.    */
  827.  
  828.     if (binary || no_details_flag)
  829.         {
  830.         int differs = (filevec[0].buffered_chars != filevec[1].buffered_chars
  831.                      || bcmp (filevec[0].buffer, filevec[1].buffer,
  832.                           filevec[1].buffered_chars));
  833.         if (differs) 
  834.             message (binary ? "Binary files %s and %s differ\n"
  835.          : "Files %s and %s differ\n",
  836.                  filevec[0].name, filevec[1].name);
  837.  
  838.         *file_differs = 1;
  839.         return NULL;
  840.         }
  841.  
  842.   /* Allocate vectors for the results of comparison:
  843.      a flag for each line of each file, saying whether that line
  844.      is an insertion or deletion.
  845.      Allocate an extra element, always zero, at each end of each vector.  */
  846.  
  847.     filevec[0].changed_flag = (char *) xmalloc (filevec[0].buffered_lines + 2);
  848.     filevec[1].changed_flag = (char *) xmalloc (filevec[1].buffered_lines + 2);
  849.     bzero (filevec[0].changed_flag, filevec[0].buffered_lines + 2);
  850.     bzero (filevec[1].changed_flag, filevec[1].buffered_lines + 2);
  851.   filevec[0].changed_flag++;
  852.   filevec[1].changed_flag++;
  853.  
  854.   /* Some lines are obviously insertions or deletions
  855.      because they don't match anything.  Detect them now,
  856.      and avoid even thinking about them in the main comparison algorithm.  */
  857.  
  858.   error = discard_confusing_lines (filevec);
  859.   if ( error )
  860.     goto    done;
  861.  
  862.   /* Now do the main comparison algorithm, considering just the
  863.      undiscarded lines.  */
  864.  
  865.   xvec = filevec[0].undiscarded;
  866.   yvec = filevec[1].undiscarded;
  867.   diags = filevec[0].nondiscarded_lines + filevec[1].nondiscarded_lines + 3;
  868.     fdiag = (LONG *) xmalloc (diags * sizeof (*fdiag));
  869.  
  870.     if ( ! fdiag )
  871.     {
  872.         error = memory_err;
  873.         goto    done;
  874.     }
  875.  
  876.   fdiag += filevec[1].nondiscarded_lines + 1;
  877.     bdiag = (LONG *) xmalloc (diags * sizeof (*bdiag));
  878.     if ( ! bdiag )
  879.     {
  880.         error = memory_err;
  881.         goto    done;
  882.     }
  883.  
  884.   bdiag += filevec[1].nondiscarded_lines + 1;
  885.  
  886.   files[0] = filevec[0];
  887.   files[1] = filevec[1];
  888.  
  889.     error = compareseq ((LONG)0, filevec[0].nondiscarded_lines,
  890.         (LONG)0, filevec[1].nondiscarded_lines);
  891.  
  892. done:
  893.     if ( bdiag )
  894.     {
  895.   bdiag -= filevec[1].nondiscarded_lines + 1;
  896.   free (bdiag);
  897.   bdiag = NULL;
  898.     }
  899.  
  900.     if ( fdiag )
  901.     {
  902.   fdiag -= filevec[1].nondiscarded_lines + 1;
  903.   free (fdiag);
  904.   fdiag = NULL;
  905.     }
  906.  
  907.   /* Modify the results slightly to make them prettier
  908.      in cases where that can validly be done.  */
  909.  
  910.     if ( ! error )
  911.     {
  912.         shift_boundaries (filevec);
  913.  
  914.   /* Get the results of comparison in the form of a chain
  915.      of `struct change's -- an edit script.  */
  916.  
  917.   if (output_style == OUTPUT_ED)
  918.     script = build_reverse_script (filevec);
  919.   else
  920.     script = build_script (filevec);
  921.     }
  922.     
  923.   for (i = 1; i >= 0; --i)
  924.     {
  925.       free (filevec[i].realindexes);
  926.       free (filevec[i].undiscarded);
  927.     }
  928.  
  929.   for (i = 1; i >= 0; --i)
  930.   {
  931.     if ( filevec[i].changed_flag )
  932.     free (--filevec[i].changed_flag);
  933.   }
  934.  
  935.   for (i = 1; i >= 0; --i)
  936.     free (filevec[i].equivs);
  937.  
  938.     return (script);
  939.     }
  940.  
  941. int
  942. print_results (filevec, script, depth)
  943.     struct file_data    filevec[2];
  944.     register    struct    change    *script;
  945.     {
  946.   int changes;
  947.   int i;
  948.     if (script || output_style == OUTPUT_IFDEF)
  949.     {
  950.       setup_output (files[0].name, files[1].name, depth);
  951.  
  952.       switch (output_style)
  953.     {
  954.     case OUTPUT_CONTEXT:
  955.       print_context_header (files, 0);
  956.       print_context_script (script, 0);
  957.       break;
  958.  
  959.     case OUTPUT_UNIFIED:
  960.       print_context_header (files, 1);
  961.       print_context_script (script, 1);
  962.       break;
  963.  
  964.     case OUTPUT_ED:
  965.       print_ed_script (script);
  966.       break;
  967.  
  968.     case OUTPUT_FORWARD_ED:
  969.       pr_forward_ed_script (script);
  970.       break;
  971.  
  972.     case OUTPUT_RCS:
  973.       print_rcs_script (script);
  974.       break;
  975.  
  976.     case OUTPUT_NORMAL:
  977.       print_normal_script (script);
  978.       break;
  979.  
  980.     case OUTPUT_IFDEF:
  981.       print_ifdef_script (script);
  982.       break;
  983.     }
  984.  
  985.       finish_output ();
  986.     }
  987.  
  988.   /* Set CHANGES if we had any diffs that were printed.
  989.      If some changes are being ignored, we must scan the script to decide.  */
  990.   if (ignore_blank_lines_flag || ignore_regexp)
  991.     {
  992.       struct change *next = script;
  993.       changes = 0;
  994.  
  995.       while (next && changes == 0)
  996.     {
  997.       struct change *this, *end;
  998.       LONG first0, last0, first1, last1, deletes, inserts;
  999.  
  1000.       /* Find a set of changes that belong together.  */
  1001.       this = next;
  1002.       end = find_change (next);
  1003.  
  1004.       /* Disconnect them from the rest of the changes,
  1005.          making them a hunk, and remember the rest for next iteration.  */
  1006.       next = end->link;
  1007.       end->link = NULL;
  1008.  
  1009.       /* Determine whether this hunk was printed.  */
  1010.       analyze_hunk (this, &first0, &last0, &first1, &last1,
  1011.             &deletes, &inserts);
  1012.  
  1013.       /* Reconnect the script so it will all be freed properly.  */
  1014.       end->link = next;
  1015.  
  1016.       if (deletes || inserts)
  1017.         changes = 1;
  1018.     }
  1019.     }
  1020.   else
  1021.     changes = (script != 0);
  1022.  
  1023. #ifndef    EXCLUDE_MAIN
  1024.   if (! ROBUST_OUTPUT_STYLE (output_style)
  1025.       /* For -D, invent newlines silently.  That's ok in C code.  */
  1026.       && output_style != OUTPUT_IFDEF)
  1027.     for (i = 0; i < 2; ++i)
  1028.       if (filevec[i].missing_newline)
  1029.     {
  1030.       error ("No newline at end of file %s", filevec[i].name, "");
  1031.       changes = 2;
  1032.     }
  1033. #endif    EXCLUDE_MAIN
  1034.  
  1035.     /* @@@@@ Print_Script needs to return a value, and
  1036.    the callers need to check this value.  This is because
  1037.    some errors can be detected AFTER printing! */
  1038.   return changes;
  1039.  
  1040.     }
  1041.  
  1042. void
  1043. dispose_script (script)
  1044.     struct    change    *script;
  1045.     {
  1046.     register struct change *e, *p;
  1047.  
  1048.   for (e = script; e; e = p)
  1049.     {
  1050.       p = e->link;
  1051.       free (e);
  1052.     }
  1053. }
  1054.